package com.gcit.seniorWish.web.modular.portal.controller;

import static com.gcit.seniorWish.core.support.HttpKit.getIp;
import static com.gcit.seniorWish.core.support.HttpKit.getRequest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import cn.hutool.core.util.StrUtil;
import com.gcit.seniorWish.core.exception.GunsException;
import com.gcit.seniorWish.web.common.constant.enums.ExamineeStatusEnum;
import com.gcit.seniorWish.web.common.constant.enums.NoticeTypeEnum;
import com.gcit.seniorWish.web.common.constant.enums.SystemConfigurateEnum;
import com.gcit.seniorWish.web.common.constant.enums.UserTypeEnum;
import com.gcit.seniorWish.web.common.constant.factory.ConstantFactory;
import com.gcit.seniorWish.web.common.persistence.model.*;
import com.gcit.seniorWish.web.config.properties.BussProperties;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorExamineeService;
import com.gcit.seniorWish.web.modular.examinee.service.impl.SeniorExamineeServiceImpl;
import com.gcit.seniorWish.web.modular.inputMidScore.service.IExamineeScoreService;
import com.gcit.seniorWish.web.modular.portal.service.ISeniorWishService;
import com.gcit.seniorWish.web.modular.system.service.INoticeService;
import com.gcit.seniorWish.web.modular.system.service.IUserMgrService;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.Condition;
import com.gcit.seniorWish.core.base.controller.BaseController;
import com.gcit.seniorWish.core.util.ToolUtil;
import com.gcit.seniorWish.web.config.properties.GunsProperties;
import com.gcit.seniorWish.web.core.exception.BizExceptionEnum;
import com.gcit.seniorWish.web.core.log.LogManager;
import com.gcit.seniorWish.web.core.log.factory.LogTaskFactory;
import com.gcit.seniorWish.web.core.shiro.ShiroKit;
import com.gcit.seniorWish.web.core.shiro.ShiroUser;
import com.google.code.kaptcha.Constants;

/**
 * 门户学生报考志愿控制器
 *
 * @author tl
 * @Date 2017年2月12日21:59:14
 */
@Controller
@RequestMapping("/portal")
public class PortalIndexController extends BaseController {

	private Logger log = LoggerFactory.getLogger(this.getClass());


	private static String PREFIX = "/portal";

	@Autowired
	private GunsProperties gunsProperties;


	@Resource
	private IUserMgrService userMgrService;

	@Autowired
	private ISeniorWishService seniorWishService;

	@Autowired
	private ISeniorExamineeService seniorExamineeService;

	@Autowired
	private IExamineeScoreService examineeScoreService ;

	@Autowired
	private INoticeService noticeService;

	/**
	 * 跳转到首页
	 */
	@RequestMapping("")
	public String index(Model model) {
		ShiroUser shiroUser = ShiroKit.getUser();
		if (shiroUser.getType() != UserTypeEnum.EXAMINEE.getValue()) {
			throw new GunsException(BizExceptionEnum.NOT_EXAMINEE);
		}
		// 根据学生的准考证号查询出考生信息
		SeniorExaminee examinee = seniorExamineeService.getExamineeByExamCardNumberWithSchoolClassName(shiroUser.getAccount());
		if(examinee==null){
			ShiroKit.getSubject().logout();
			model.addAttribute("message","账号已失效，请重新登陆");
			return PREFIX + "/login.html";
		}
		model.addAttribute("examinee", examinee);
		return PREFIX + "/index.html";
	}

	/**
	 * 跳转到登录页面
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(Model model) throws ParseException {
		//如果存在sessionstatus存在并且值为timeout.则认为登录超时跳转过来的
		if(StrUtil.isNotBlank(super.getPara("sessionstatus"))&&super.getPara("sessionstatus").equals("timeout")){
			model.addAttribute("message","登录超时");
			return PREFIX + "/login.html";
		}
		SystemConfigurate configurate = ConstantFactory.me().getSystemConfigurateByKey(SystemConfigurateEnum.SENIOR_WISH_END_DATE.getMessage());
			if (configurate != null) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日HH点");
				Date wishEndDate = sdf.parse(configurate.getConfigurateValue()+":00:00");
				// 判断当前时间是否大于截止时间
				if ((new Date().getTime() - wishEndDate.getTime()) > 0) {// 大于不能登录填报系统
					model.addAttribute("message", "本系统于"+sdf1.format(wishEndDate)+"禁止考生登录");
					model.addAttribute("messageFalg", "flag");
					return PREFIX + "/login.html";
				}
		}
		if (ShiroKit.isAuthenticated() || ShiroKit.getUser() != null) {
			return PREFIX + "/";
		} else {
			return PREFIX + "/login.html";
		}
	}

	/**
	 * 登录验证
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String loginVali(Model model) throws ParseException {
		SystemConfigurate configurate = ConstantFactory.me().getSystemConfigurateByKey(SystemConfigurateEnum.SENIOR_WISH_END_DATE.getMessage());
		if (configurate != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日HH点");
			Date wishEndDate = sdf.parse(configurate.getConfigurateValue()+":00:00");
			// 判断当前时间是否大于截止时间
			if ((new Date().getTime() - wishEndDate.getTime()) > 0) {// 大于不能登录填报系统
				model.addAttribute("message", "本系统于"+sdf1.format(wishEndDate)+"禁止考生登录");
				model.addAttribute("messageFalg", "flag");
				return PREFIX + "/login.html";
			}
		}

		String username = super.getPara("username").trim();
		String password = super.getPara("password").trim();
		log.info("门户登陆，用户名："+username);
		// 验证验证码是否正确
		if (gunsProperties.getKaptchaPortalOpen()) {
			String kaptcha = super.getPara("kaptcha").trim();
			String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
			if (ToolUtil.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
				model.addAttribute("message", "验证码错误");
				return PREFIX + "/login.html";
			}
		}
		Subject currentUser = ShiroKit.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());
		currentUser.login(token);
		ShiroUser shiroUser = ShiroKit.getUser();
		if (shiroUser.getType() != UserTypeEnum.EXAMINEE.getValue()) {
			currentUser.logout();
			model.addAttribute("message", "登陆用户非考生");
			log.info("门户登录失败，登陆用户非考生。用户名："+username);
			LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), "登陆用户非考生",getIp()));
			return PREFIX + "/login.html";
		}
		super.getSession().setAttribute("shiroUser", shiroUser);
		super.getSession().setAttribute("username", shiroUser.getAccount());
		LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), getIp()));
		ShiroKit.getSession().setAttribute("sessionFlag", true);
		return REDIRECT + PREFIX + "/reporteNotice";
	}

	/**
	 * 退出登录
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logOut() {
		LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), getIp()));
		ShiroKit.getSubject().logout();
		return REDIRECT+PREFIX + "/login";
	}

	/**
	 * 跳转到填报须知
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/reporteNotice")
	public String reporteNotice() {
		ShiroUser shiroUser = ShiroKit.getUser();
		if (shiroUser.getType() != UserTypeEnum.EXAMINEE.getValue()) {
			throw new GunsException(BizExceptionEnum.NOT_EXAMINEE);
		}
		List<Notice> notices = noticeService
				.selectList(Condition.create().eq("type", NoticeTypeEnum.REPORT_NOTICE.getVal()));
		Notice notice = new Notice();
		if (notices.size() > 0)
			notice = notices.get(0);
		super.setAttr("notice", notice);
		return PREFIX + "/reporte_notice.html";
	}

	/**
	 * 修改密码
	 */
	@RequestMapping("/changePwd")
	public String changepwd(Model model) {
		ShiroUser shiroUser = ShiroKit.getUser();
		if (shiroUser.getType() != UserTypeEnum.EXAMINEE.getValue()) {
			throw new GunsException(BizExceptionEnum.NOT_EXAMINEE);
		}
		// 根据学生的准考证号查询出考生信息
		SeniorExaminee examinee = seniorExamineeService.getExamineeByExamCardNumberWithSchoolClassName(shiroUser.getAccount());
		if(examinee==null){
			ShiroKit.getSubject().logout();
			model.addAttribute("message","账号已失效，请重新登陆");
			return PREFIX + "/login.html";
		}
		model.addAttribute("examinee", examinee);
		return PREFIX + "/changepwd.html";
	}

	/**
	 * 修改当前用户的密码
	 */
	@RequestMapping("/changePwdSave")
	@ResponseBody
	public String changePwd(@RequestParam String oldPwd, @RequestParam String newPwd, @RequestParam String rePwd) {
		if (!newPwd.equals(rePwd)) {
			throw new GunsException(BizExceptionEnum.TWO_PWD_NOT_MATCH);
		}
		String userId = ShiroKit.getUser().getId();
		User user = userMgrService.selectById(userId);
		String oldMd5 = ShiroKit.md5(oldPwd, user.getSalt());
		if (user.getPassword().equals(oldMd5)) {
			String newMd5 = ShiroKit.md5(newPwd, user.getSalt());
			user.setPassword(newMd5);
			user.updateById();
			return "success";
		} else {
			throw new GunsException(BizExceptionEnum.OLD_PWD_NOT_RIGHT);
		}
	}

	/**
	 * 查看志愿，根据考生当前志愿填报的情况跳转不同的页面
	 */
	@RequestMapping(value = "/checkWish", method = RequestMethod.GET)
	public String checkWish(Model model) throws IllegalAccessException {
		ShiroUser shiroUser = ShiroKit.getUser();
		if (shiroUser.getType() != UserTypeEnum.EXAMINEE.getValue()) {
			throw new GunsException(BizExceptionEnum.NOT_EXAMINEE);
		}
		// 根据学生的准考证号查询出考生信息
		SeniorExaminee examinee = seniorExamineeService.getExamineeByExamCardNumberWithSchoolClassName(shiroUser.getAccount());
		if(examinee==null){
			ShiroKit.getSubject().logout();
			model.addAttribute("message","账号已失效，请重新登陆");
			return PREFIX + "/login.html";
		}
		model.addAttribute("examinee", examinee);
		// 未填报跳转填报页面
		if (examinee.getWriteStatus() == ExamineeStatusEnum.NOT_YET_WRITE.getValue()) {
			return PREFIX + "/wish_report.html"; //没有填报志愿信息 跳转到填报志愿页面
		} else {
			model.addAttribute("seniorWish", seniorWishService.seniorWishDetail(examinee.getExamCardNumber()));
			return PREFIX + "/wish_check.html";
		}
	}

	/**
	 * 跳转修改志愿页面
	 */
	@RequestMapping(value = "/changeWish", method = RequestMethod.GET)
	public String changeWish(Model model) throws IllegalAccessException {
		ShiroUser shiroUser = ShiroKit.getUser();
		if (shiroUser.getType() != UserTypeEnum.EXAMINEE.getValue()) {
			throw new GunsException(BizExceptionEnum.NOT_EXAMINEE);
		}
		// 根据学生的准考证号查询出考生信息
		SeniorExaminee examinee = seniorExamineeService.getExamineeByExamCardNumberWithSchoolClassName(shiroUser.getAccount());
		if(examinee==null){
			ShiroKit.getSubject().logout();
			model.addAttribute("message","账号已失效，请重新登陆");
			return PREFIX + "/login.html";
		}
		model.addAttribute("examinee", examinee);
		model.addAttribute("seniorWish", seniorWishService.seniorWishDetail(examinee.getExamCardNumber()));
		// 未填报跳转填报页面
		return PREFIX + "/wish_report.html";
	}

	/**
	 * 提交填报
	 *
	 * @param seniorWish
	 *            志愿信息
	 * @author gaozhichang
	 * @date 2018-03-23 上午 9:06
	 */
	@RequestMapping(value = "/reportWish", method = RequestMethod.POST)
	@ResponseBody
	public Object reportWish(SeniorWish seniorWish) throws IllegalAccessException {
		if (ShiroKit.getUser().getType() != UserTypeEnum.EXAMINEE.getValue()) {
			throw new GunsException(BizExceptionEnum.NOT_EXAMINEE);
		}
		seniorWish.setExamCardNumber(ShiroKit.getUser().getAccount());
		seniorWishService.mergeSeniorWish(seniorWish);
		return SUCCESS_TIP;
	}

	/**
	 * 确认志愿
	 *
	 * @author gaozhichang
	 * @date 2018-03-25 下午 2:50
	 */
	@RequestMapping(value = "/confirmWish")
	@ResponseBody
	public Object confirmWish() {
		if (ShiroKit.getUser().getType() != UserTypeEnum.EXAMINEE.getValue()) {
			throw new GunsException(BizExceptionEnum.NOT_EXAMINEE);
		}
		seniorWishService.confirmSeniorWish(ShiroKit.getUser().getAccount());
		return SUCCESS_TIP;
	}


    /**
     * 跳转查分页面
     *
     * @author gaozhichang
     * 	@date 2018年5月2日09:10:55
     * @return
     */
    @RequestMapping("/scoreInquiry")
	public String scoreInquiry(String kaptcha ,String examCardNumber,String examSiteNumber,String seatNumber,Model model){
    	//当没有传递准考证号时，跳转输入页面
    	if(StrUtil.isBlank(examCardNumber)){
			return PREFIX+"/scoreInquiryInput.html";
		}
		if(StrUtil.isBlank(examSiteNumber)||StrUtil.isBlank(seatNumber)){
    		model.addAttribute("message","请正确输入考场号与座位号");
    		return PREFIX+"/scoreInquiryInput.html";
		}

		// 验证验证码是否正确
		if (gunsProperties.getKaptchaScoreOpen()) {

			String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
			if (ToolUtil.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
				model.addAttribute("message", "验证码错误");
				return PREFIX + "/scoreInquiryInput.html";
			}
		}
		SeniorExaminee examinee = seniorExamineeService.getExamineeByExamCardNumberWithSchoolClassName(examCardNumber);
    	if(examinee==null){
    		model.addAttribute("message","未查询到匹配的考生");
    		return PREFIX+"/scoreInquiryInput.html";
		}
		ExamineeScore score = examineeScoreService.getExamineeScore(examCardNumber);
    	if(score==null){
			model.addAttribute("message","该考生暂无成绩信息");
			return PREFIX+"/scoreInquiryInput.html";
		}
		//当座位号与准考证号不同时，返回学生数据的提示
    	if(!examSiteNumber.equals(score.getExamSiteNumber())||!seatNumber.equals(score.getSeatNumber())){
			model.addAttribute("message","未查询到匹配的考生");
			return PREFIX+"/scoreInquiryInput.html";
		}
		examinee.setExamineeScore(score);
		model.addAttribute("examinee",examinee);
		return PREFIX+"/scoreInquiry.html";
    }
}
